<template>
	<div>

		<!--购物车-->
		<br /><br />
		<center>
		<table>
			
			<tr v-for="(item,index) in cart">
				
				<td>{{ item.name }}</td>

				<td>

					<Button @click="add(index,'-')" color="blue">-</Button>

				{{ item.num }}

					<Button @click="add(index,'+')" color="blue">+</Button>

				</td>

				<td>{{ item.price}}</td>


				<td><Button @click="del(index)" color="red">删除</Button></td>


			</tr>


		</table>

		<br />

		<Button @click="add_cart('汽车')">添加汽车</Button>

		&nbsp;&nbsp;

		您购物车里的数量为 {{ totalCount() }}

		&nbsp;&nbsp;

		<Button @click="des" color="red">清空购物车</Button>

		</center>

		<!--监听属性-->

		<button @click="counter--">点我++</button>

		{{ reverse_msg }}

		<!--绑定样式-->
		<div :class="{ active:isactive }" ></div>


		<!--遍历展示-->

		<ul>
			
			<li v-for='(item,index) in tlist' :class="{on:index%2==0,off:index%2!=0}" >
				
				{{ item.text }} 

			</li>

		</ul>


		<div v-if="type === 'A'">
			
			A

		</div>

		<div v-else-if = "type === 'B'">
				
			B

		</div>

		<div v-else>
			
			C

		</div>


		<h1 v-show = "ok">你看见我了</h1>

		{{ msg }}
		
	</div>
</template>

<script>
	
	export default{

		data(){

			return{

				msg:'你好，这里是vue',
				ok:0,
				type:'B',
				tlist:[{text:'汽车',price:10},{text:'手机'},{text:'电脑'},{text:'食品'}],
				//购物车
				cart:[{name:'手机',price:10,num:0},{name:'电脑',price:50,num:0}],
				isactive:false,
				counter:0

			}
		},
		//监听属性
		watch:{

			counter:function(nval,oval){

					console.log('计数器的变化:'+'从'+ oval + '变成了' + nval);

			}

		},
		//计算属性
		computed:{

			//反转
			reverse_msg:function(){

				return '$'+this.msg.split('').reverse().join('');

			}

		},
		//自定义方法
		methods:{

			//清空购物车
			des:function(){

				this.cart = [];
			},
			//删除操作
			del:function(index){

					//根据下标删除元素
					this.cart.splice(index,1);
			},
			//汇总数量
			totalCount:function(){

				//默认值
				let total = 0;
				//遍历
				for(let i=0,l=this.cart.length;i<l;i++){

					//累加
					total += (this.cart[i].num * this.cart[i].price);

				}

				return total;
			},
			//加减法
			add:function(index,type){

				if(type == '+'){

				this.cart[index].num++;

				}else{

					if(this.cart[index].num > 0){

				this.cart[index].num--;
				}

				}


			},
			//添加购物车方法
			add_cart:function(name){

				//声明购物车变量
				let cartlist = this.cart;
				//声明坐标
				let find = 0;
				//遍历购物车列表
				for(let i=0,l=cartlist.length;i<l;i++){

					//判断
					if(name == cartlist[i]['name']){

						cartlist[i]['num']++;
						find = 1;
						break;
					}

				}
				//没找到
				if(find == 0){
					cartlist.push({name:name,num:1,price:100})
				}
				//赋值
				this.cart = cartlist;

			}


		}


	}

</script>

<style>

.on {background:black;}
.off {background:red;}
.active{

	width:100px;
	height:200px;
	background:yellow;
}
</style>